﻿using Easy.Services.DbContexts;
using Easy.Services.Dtos;
using Easy.Services.Entities;
using Easy.Services.Interface;
using System.Linq.Expressions;

namespace Easy.Services.Core
{
    internal class DatabaseService: IDatabaseService
    {

        public long Add(Database model)
        {
            using MySQLDbContext db = new();
            BaseService<Database> baseService = new(db);
            return baseService.AddBase(model);

        }

        public List<Database> GetList(Expression<Func<Database, bool>> expression = null)
        {
            using MySQLDbContext db = new();
            BaseService<Database> baseService = new(db);
            return baseService.GetList(expression);

        }

        public DataBaseStatisticsDTO GetStatistics(Expression<Func<Database, bool>> expression = null)
        {
            DataBaseStatisticsDTO dto = new();
            int count = 11;
            DateTime time = DateTime.Now;
            DateTime startTime = DateTime.Now.AddMonths(-count).AddDays(-time.Day).Date;
            var queryData = this.GetList(i => i.CreaterDate > startTime);
            List<string> xAxisData = [];
            List<string> aData = [];
            List<string> dData = [];
            List<string> uData = [];
            List<string> qData = [];
            var queryGroup = queryData.GroupBy(q => q.CreaterDate.Value.ToString("yyyy-MM"));
            foreach (var item in queryGroup)
            {
                xAxisData.Add(item.Key);
                aData.Add(item.Where(i => i.Type == 1).Count().ToString());
                dData.Add(item.Where(i => i.Type == 2).Count().ToString());
                uData.Add(item.Where(i => i.Type == 3).Count().ToString());
                qData.Add(item.Where(i => i.Type == 4).Count().ToString());
            }
            dto.XAxisData = [.. xAxisData];
            dto.AddData = [.. aData];
            dto.DeleteData = [.. dData];
            dto.UpdateData = [.. uData];
            dto.QueryData = [.. qData];

            DateTime startStorageTime = DateTime.Now.AddDays(-14).Date;
            var queryStorageData = this.GetList(i => i.CreaterDate > startTime);
            var queryStorageGroup = queryStorageData.GroupBy(q => q.CreaterDate.Value.ToString("yyyy-MM-dd"));
            List<string> xStorageData = [];
            List<string> sStorageData = [];
            foreach (var item in queryStorageGroup)
            {
                xStorageData.Add(item.Key);
                sStorageData.Add(item.LastOrDefault()?.Storage ?? "0");
            }
            dto.XAxisStorageData = [.. xStorageData];
            dto.SeriesStorageData = [.. sStorageData];
            return dto;
        }

    }
}
